<template>
  <!-- 附件上传控件 -->
  <div>
    <div class="form-components">
      <div v-if="readonly" class="form-readonly"></div>
      <el-upload
        class="upload-demo"
        :action="action"
        :download="download"
        :multiple="multiple"
        :name="name"
        :accept="accept"
        :limit="limit"
        :file-list="fileList"
        :before-upload="beforeUpload"
        :on-success="onSuccess"
        :on-error="onError"
        :show-file-list="false"
      >
        <el-button size="small" type="primary" :disabled="disabled" :loading="loading">点击上传</el-button>
        <div v-if="__config__.showTip" slot="tip" class="el-upload__tip">*{{ tips }}</div>
      </el-upload>
    </div>
    <FilesShow
      v-if="fileList.length"
      :value.sync="fileList"
      isEdit
      :readonly="readonly || disabled"
      :dName="dName"
      :download="download"
      style="margin-top: 10px"
      @change="handleChange"
    />
  </div>
</template>
<script>
import FilesShow from "./components/filesShow";
import ImageShow from "./components/imageShow";

export default {
  name: "form-upload",
  model: {
    prop: "value", // 绑定的值，通过父组件传递
    event: "update"
  },
  components: {
    FilesShow,
    ImageShow
  },
  props: {
    // 绑定的输入值
    value: {
      type: [String, Number],
      default: ""
    },
    // 是否只读
    readonly: {
      type: Boolean,
      default: false
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 表单属性
    __config__: {
      type: Object,
      default: () => {}
    },
    // 文件类型
    accept: {
      type: String,
      default: ""
    },
    // 文件上传地址
    action: {
      type: String,
      default: ""
    },
    // 文件下载地址
    download: {
      type: String,
      default: ""
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 	上传的文件字段名
    name: {
      type: String,
      default: ""
    },
    // 	下载的文件字段名
    dName: {
      type: String,
      default: ""
    },
    // 最大允许上传个数
    limit: {
      type: Number,
      default: 10
    }
  },
  computed: {
    tips() {
      // 最大上传文件+单位
      const sizeUnit = this.__config__.fileSize + this.__config__.sizeUnit;
      if (this.accept) {
        return `只能上传${this.accept}文件，且不超过${sizeUnit}的文件`;
      }
      return `只能上传不超过${sizeUnit}的文件`;
    }
  },
  data() {
    return {
      fileList: [
        // {
        //   name: "food.jpeg",
        //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        // },
        // {
        //   name: "food2.jpeg",
        //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        // },
      ],
      loading: false
    };
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler: function(nd, od) {
        try {
          // 回显
          this.fileList = JSON.parse(nd) || [];
        } catch (error) {
          console.log("error", error);
        }
      }
    }
  },
  methods: {
    beforeUpload(file) {
      if (this.fileList.length >= this.limit) {
        this.$message({
          message: `最多允许上传${this.limit}个文件`,
          type: "info"
        });
        return false;
      }
      const fileSize = this.__config__.fileSize; // 文件大小
      const fileUnit = this.__config__.sizeUnit; // 文件单位
      // 实际上传的文件大小单位为B，需要将文件大小限制的单位转换为B
      const maxSize =
        fileSize *
        { KB: 1024, MB: Math.pow(1024, 2), GB: Math.pow(1024, 3) }[fileUnit];
      let isLt = file.size < maxSize; // 判断是否超过文件大小
      if (!isLt) {
        this.$message({
          message: `请上传小于${fileSize + fileUnit}的文件!`,
          type: "info"
        });
        return false;
      } else {
        this.loading = true;
        return true;
      }
    },
    // 上传成功
    onSuccess(data) {
      let res = data.result;
      try {
        res.mFilePath.forEach((path, index) => {
          this.fileList.push({
            id: res.idList[index],
            name: res.mFileName[index],
            url: path
          });
        });
        this.handleChange(this.fileList);
        this.$message({
          message: `上传成功！`,
          type: "success"
        });
        this.loading = false;
      } catch (error) {
        this.onError();
      }
    },
    // 上传失败
    onError() {
      this.$message({
        message: `上传失败！`,
        type: "error"
      });
      this.loading = false;
    },

    handleChange(fileArr) {
      this.$emit("update", fileArr.length ? JSON.stringify(fileArr) : null);
    }
  }
};
</script>
